package stack;

/**
 * 用数组类模拟一个栈
 * @Auther Jun jie Yi
 * @Date 21:08 2021/7/6
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        //测试
        ArrayStack arrayStack = new ArrayStackDemo().new ArrayStack(4);
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        arrayStack.push(4);
        arrayStack.list();
        System.out.println(arrayStack.pop());
        arrayStack.list();
    }
    //定义这个类表示栈结构
    class ArrayStack{
        private int maxSize; //栈的大小
        private int[] stack; //数组，这里用数组模拟栈
        private int top = -1; //没有数据时，初始化栈顶下标为 -1
        //构造器
        public ArrayStack(int maxSize) {
            this.maxSize = maxSize;
            stack = new int[this.maxSize];
        }
        //栈满
        public boolean isFull() {
            return top == maxSize - 1;
        }
        //栈空
        public boolean isEmpty() {
            return top == -1;
        }
        //入栈 push
        public void push(int value) {
            //判断栈是否已经满了
            if(isFull()) {
                System.out.println("栈满");
            } else {
                stack[++ top] = value;
            }
        }
        //出栈 pop
        public int pop() {
            //判断栈是否已经满了
            if(isEmpty()) {
                throw new RuntimeException("栈为空");
            } else {
                int value = stack[top];
                top --;
                return value;
            }
        }
        //遍历整个栈
        public void list() {
            if(isEmpty()) {
                System.out.println("栈空，无法遍历");
                return;
            } else {
                //需要从栈顶开始显示数据
                for (int i = top; i >= 0; i--) {
                    System.out.printf("stack[%d]=%d\n", i, stack[i]);
                }
            }
        }
    }
}
